package com.shirley.serialportlib;

import android.util.Log;

import com.shirley.serialportlib.listener.OnSerialPortOpenListener;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Description: 串口管理
 * Created by Shirley on 2019/12/05.
 * Author: Kongqw
 */
public class SerialPortManager extends SerialPort {

    private static final String TAG =  SerialPortManager.class.getSimpleName();
    /*
     * Do not remove or rename the field mFd: it is used by native method close();
     */
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;
    private OnSerialPortOpenListener mOpenListener;

    /**
     * 打开串口
     * @param device 串口地址
     * @param baudRate 串口波特率
     * @return 结果
     */
    public boolean openSerialPort(File device, int baudRate) {
        // 检查串口权限
        if (!device.canRead() || !device.canWrite()) {
            boolean chmod666 = chmod666(device);
            if (!chmod666) {
                Log.i(TAG, "openSerialPort：没有读写权限");
                if (mOpenListener != null) {
                    mOpenListener.onFail(device, OnSerialPortOpenListener.Status.WITHOUT_READ_WRITE_PERMISSION);
                }
                return false;
            }
        }

        try {
            mFd = open(device.getAbsolutePath(), baudRate, 0);
            mFileInputStream = new FileInputStream(mFd);
            mFileOutputStream = new FileOutputStream(mFd);
            if (mOpenListener != null) {
                mOpenListener.onSuccess(device);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            if (mOpenListener != null) {
                mOpenListener.onFail(device, OnSerialPortOpenListener.Status.OPEN_FAIL);
            }
        }
        return false;
    }

    /**
     * 关闭串口
     */
    public void closeSerialPort(){
        if (mFd != null) {
            close();
            mFd = null;
        }
        if (mFileInputStream != null) {
            try {
                mFileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mFileInputStream = null;
        }
        if (mFileOutputStream != null) {
            try {
                mFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mFileOutputStream = null;
        }
        mOpenListener = null;
    }

    /**
     * 设置串口打开监听器
     * @param listener
     * @return
     */
    public SerialPortManager setSerialPortOpenListener(OnSerialPortOpenListener listener) {
        this.mOpenListener = listener;
        return this;
    }

}
